package com.hkd.friend.service.user.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hkd.common.core.constants.Constants;
import com.hkd.common.core.domain.R;
import com.hkd.common.core.domain.TableDataInfo;
import com.hkd.common.core.enums.ExamListType;
import com.hkd.common.core.enums.ResultCode;
import com.hkd.common.core.utils.ThreadLocalUtil;
import com.hkd.common.security.service.TokenService;
import com.hkd.friend.domain.exam.Exam;
import com.hkd.friend.domain.exam.dto.ExamDTO;
import com.hkd.friend.domain.exam.dto.ExamQueryDTO;
import com.hkd.friend.domain.exam.vo.ExamVO;
import com.hkd.friend.domain.user.UserExam;
import com.hkd.friend.manager.ExamCacheManager;
import com.hkd.friend.mapper.exam.ExamMapper;
import com.hkd.friend.mapper.user.UserExamMapper;
import com.hkd.friend.service.user.IUserExamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class UserExamServiceImpl implements IUserExamService {
    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Value("${jwt.secret}")
    private String secret;
    @Override
    public R enter(String token, ExamDTO examDTO) {
        //1.校竞赛赛是否存在
        Exam exam = examMapper.selectById(examDTO.getExamId());
        if (exam == null) {
            log.error("赛赛不存在");
            return R.failed(ResultCode.FAILED_EXAM_NOT_EXISTS);
        }
        //2.竞赛是否开始
        if (exam.getStartTime().isBefore(LocalDateTime.now())) {
            log.error("赛赛已开始");
            return R.failed(ResultCode.FAILED_EXAM_HAS_START);
        }
        //token解析
//        Long userId = tokenService.getUserIdFT(token, secret);
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        log.info("userId:{}",userId);

        //3.用户是否已经参加过该赛赛
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examDTO.getExamId())
                .eq(UserExam::getUserId, userId));
        if (userExam != null) {
            log.error("不能重复报名");
            return R.failed(ResultCode.FAILED_EXAM_USER_HAS_ENTER);
        }
        //4.添加用户赛赛记录
        //缓存添加
        examCacheManager.addUserExamCache(userId, examDTO.getExamId());
        //数据库添加
        userExam = new UserExam();
        userExam.setExamId(examDTO.getExamId());
        userExam.setUserId(userId);
        int insert = userExamMapper.insert(userExam);
        if(insert <= 0){
            log.error("添加赛赛记录失败");
            return R.failed(ResultCode.FAILED_EXAM_USER_ENTER);
        }

        return R.success();
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        //1.获取当前用户id
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        examQueryDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(), userId);
        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            //从数据库中查询我的竞赛列表
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(), userId);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            examVOList = examCacheManager.getExamVOList(examQueryDTO, userId);
            total = examCacheManager.getListSize(examQueryDTO.getType(), userId);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        return TableDataInfo.success(examVOList, total);
    }
}
